<template>
  <el-drawer
    :visible.sync="drawerVisible"
    :before-close="handleClose"
    :size="showMobilePage ? '100%' : '80%'"
    title="选择历史开票申请">
    <div class="drawer-content">
      <div class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          line-feed
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
      </div>
      <el-tabs v-model="curTabName" style="margin: 17px 0 8px" @tab-click="onSubActiveOrderChange">
        <el-tab-pane label="开票列表" name="all"/>
        <el-tab-pane name="selected">
          <span slot="label">已选择开票<el-badge v-if="referenceId" :value="1" /></span>
        </el-tab-pane>
      </el-tabs>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 100px;">
          <el-table
            v-if="(curTabName === 'all' && list.items.length > 0) || (curTabName === 'selected' && selectedData.length > 0)"
            ref="historyInvoiceDrawerRef"
            :data="curTabName === 'all'?list.items:selectedData"
            :height="setTableHeight"
            :row-class-name="(data) => tableRowClassName(data)"
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            @sort-change="sortMethod">
            <el-table-column width="50" align="center" fixed>
              <template slot-scope="scope">
                <el-radio
                  v-model="referenceId"
                  :label="scope.row.id"
                  class="custom-table-radio"
                  @change="handleRowChange(scope.row)"
                  @click.native="cancelSelect(scope.row)"
                >{{ '' }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column :fixed="!showMobilePage" align="left" label="审批单号" min-width="140">
              <template slot-scope="scope">
                <div v-if="scope.row.approvalNo" style="cursor:pointer;color:#406EFF;" @click="goIssueInvoiceDetail(scope.row)">
                  <ToolTip :content="scope.row.approvalNo" placement="top-start" />
                </div>
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="发票类型" width="174px">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.invoiceType" placement="top-start" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="纳税人名称" width="286px">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.taxpayerName" placement="top-start" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="我方抬头" width="286px">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.ourTitle" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="申请人">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.proposer" placement="top-start" />
              </template>
            </el-table-column>
            <el-table-column align="right" label="含税金额(元)" min-width="130" prop="amount" sortable="custom">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.amount" :price="scope.row.amount" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="开票项目" width="230px">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.project" placement="top-start" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="状态">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.status || scope.row.status=== 0" :open-delay="800" class="item" placement="top" effect="dark">
                  <div slot="content">{{ scope.row.status | invoiceStatus }}</div>
                  <div style="display:flex;align-items:center">
                    <div :class="`color-${scope.row.status}`" class="dot"/>
                    <div>{{ scope.row.status | invoiceStatus }}</div>
                  </div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="申请部门" width="140">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.departmentName" placement="top-start" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="创建人" width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.creator" placement="top-start" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="创建时间" min-width="160" prop="createTime" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm')" placement="top-start" />
              </template>
            </el-table-column>
          </el-table>
          <EmptyPlaceholder v-else style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="list.items.length && curTabName === 'all'"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="showMobilePage?'total, prev, next,jumper':'total, prev, pager, next, sizes,jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!referenceId || addLoading" size="small" type="primary" class="related-btn" @click="handleSubmit">
              确定<i v-if="addLoading" class="el-icon-loading"/>
            </el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="handleClose">返回</el-button>
          </div>
          <el-pagination
            v-if="!showMobilePage"
            v-show="list.items.length && curTabName === 'all'"
            :current-page="page"
            :page-size="perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>
<script>
// api
import { getIssueInvoiceHistoryList, getInvoiceTypes, getInvoiceProjectList, getOurTitleList } from '@/api/issueInvoice';
import { getDepartmentAll } from '@/api/config';
import { format } from '@/filters/date';
// mixins
import { numberTextFormat } from '@/filters/number';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import TableAdaptive from '@/mixins/tableAdaptive';
import { mapState } from 'vuex';
// 组件
import EmptyPlaceholder from '@/components/EmptyPlaceholder';

export default {
  components: {
    EmptyPlaceholder
  },
  filters: {
    numberTextFormat,
    invoiceStatus(status) {
      return {
        0: '草稿中',
        1: '审批中',
        2: '未过审',
        3: '已作废',
        4: '已完成',
        5: '待提交'
      }[status] || '--';
    }
  },
  mixins: [TableAdaptive],
  props: {
    queryOrderId: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      curTabName: 'all',
      format,
      list: {
        items: [],
        total: 0
      },
      referenceId: '',
      referenceApprovalNo: '',
      idKey: 'id', // 多选框参数
      tableRefName: 'historyInvoiceDrawerRef',
      page: 1,
      perPage: 20,
      paramsObj: {},
      listLoading: false,
      deptTreeList: [],
      sortName: '',
      sortType: '',
      drawerVisible: false,
      addLoading: false,
      selectedData: [],
      invoiceTypes: [], // 发票类型列表
      invoiceProjectList: [], // 开票项目列表
      ourTitleList: [] // 我方抬头列表
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    hasSelected() {
      return this.multipleSelectionAll.length;
    },
    statusList() {
      return [
        { value: 0, label: '草稿中' },
        { value: 1, label: '审批中' },
        { value: 2, label: '未过审' },
        { value: 3, label: '已作废' },
        { value: 4, label: '已完成' },
        { value: 5, label: '待提交' }
      ];
    },
    rangeKeyArr() {
      return [
        { attr: 'createTime', start: 'createTimeStart', end: 'createTimeEnd', type: 'time' },
        { attr: 'amount', start: 'amountStart', end: 'amountEnd', type: 'number' }
      ];
    },
    arrayKeyArr() {
      return ['departmentId'];
    },
    filterList() {
      return [
        // 输入框
        { keyword: 'approvalNo', name: '审批单号', labelWidth: '70px', type: 'input' },
        { keyword: 'taxpayerName', name: '纳税人名称', labelWidth: '100px', type: 'input' },
        { keyword: 'amount', name: '含税金额', labelWidth: '70px', type: 'inputRange' },
        { keyword: 'proposer', name: '申请人', labelWidth: '100px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '70px', type: 'input' },
        // 下拉
        { keyword: 'invoiceType', name: '发票类型', type: 'select', valueName: 'label', options: this.invoiceTypes },
        { keyword: 'project', name: '开票项目', type: 'select', valueName: 'label', options: this.invoiceProjectList },
        { keyword: 'ourTitle', name: '我方抬头', type: 'select', valueName: 'label', options: this.ourTitleList },
        { keyword: 'status', name: '状态', type: 'select', options: this.statusList },
        { keyword: 'departmentId', name: '申请部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        // 日期
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 280 : 225;
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow && this.curTabName === 'all') {
            this.setSelectRow(data.items);
          }
        });
      },
      deep: true
    }
  },
  created() {
    this.queryInvoiceProjectList();
    this.queryOurTitleList();
    this.getInvoiceTypes();
    this.fetchData(true);
    this.queryDeptTreeList();
  },
  methods: {
    openDrawer() {
      this.drawerVisible = true;
    },
    tableRowClassName({ row }) {
      return row['id'] === this.referenceId ? `table-selected pointer` : 'pointer';
    },
    // 发票类型
    getInvoiceTypes() {
      getInvoiceTypes({ isAll: true }).then(res => {
        if (res.code === 200) {
          const result = res.data || [];
          result.forEach(item => {
            item.value = item.id;
            item.label = item.name;
            item.isStringVal = true;
            item.name = '发票类型';
          });
          this.invoiceTypes = result;
        }
      });
    },
    // 开票项目
    queryInvoiceProjectList() {
      getInvoiceProjectList({ isAll: true }).then(res => {
        if (res.code === 200) {
          const result = res.data || [];
          result.forEach(item => {
            item.value = item.id;
            item.label = item.name;
            item.isStringVal = true;
            item.name = '开票项目';
          });
          this.invoiceProjectList = result;
        }
      });
    },
    // 我方抬头
    queryOurTitleList() {
      getOurTitleList({ isAll: true }).then(res => {
        if (res.code === 200) {
          const result = res.data || [];
          result.forEach(item => {
            item.value = item.id;
            item.label = item.name;
            item.isStringVal = true;
            item.name = '我方抬头';
          });
          this.ourTitleList = result;
        }
      });
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (data.paneName === 'all') {
        this.fetchData();
      } else {
        this.referenceId && this.querySelectedData();
      }
    },
    handleSubmit() {
      this.addLoading = true;
      const referenceData = {};
      referenceData.referenceId = this.referenceId;
      referenceData.referenceApprovalNo = this.referenceApprovalNo;
      this.$emit('submit', referenceData);
      this.handleClose();
    },
    handleClose() {
      this.drawerVisible = false;
      this.addLoading = false;
      this.referenceId = '';
      this.referenceApprovalNo = '';
      this.curTabName = 'all';
      this.selectedData = [];
    },
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData(true);
    },
    queryClick() {
      this.curTabName = 'all';
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.sortName = '';
      this.sortType = '';
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
    },
    fetchData(reset = false) {
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      params.excludeId = this.$route.params.id;
      getIssueInvoiceHistoryList(params).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    querySelectedData() {
      this.listLoading = true;
      const params = {};
      params.page = 1;
      params.perPage = 999;
      params.id = this.referenceId;
      params.excludeId = this.$route.params.id;
      getIssueInvoiceHistoryList(params).then(res => {
        this.listLoading = false;
        if (res.code === 200) {
          this.selectedData = res.data.items || [];
        }
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    formatParams() {
      const params = _.cloneDeep(this.paramsObj);
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      params.sortName = this.sortName || '';
      params.sortType = this.sortType || '';
      params.page = this.page;
      params.perPage = this.perPage;
      return params;
    },
    // 跳转开票申请详情
    goIssueInvoiceDetail(data) {
      const url = this.$router.resolve({
        name: 'issueInvoiceDetail',
        query: {
          issueId: data.id,
          processId: data.processId
        }
      });
      window.open(url.href, '_blank');
    },
    // 开票列表选中
    handleRowChange(row) {
      if (this.curTabName === 'all') {
        this.referenceId = row.id;
        this.referenceApprovalNo = row.approvalNo;
      }
    },
    // 已选择取消选中
    cancelSelect() {
      if (this.curTabName !== 'all') {
        this.referenceId = '';
        this.referenceApprovalNo = '';
        this.selectedData = [];
      }
    }
  }
};
</script>
<style lang="scss" scoped>
$bgc: #FFBC3D 0, #FD8546 1, #FF4E5F 2, #999 3, #31CC9C 4, #406EFF 5;
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
::v-deep .el-badge__content{
  background: #FB5227;
}
::v-deep .el-badge__content{
  margin-top: 18px;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .table-list {
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      align-items: center;
      .related-btn {
        margin-left: 20px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    ::v-deep .pagination-flex {
      position: absolute;
      width: 100% !important;
    }
  }
  .dot {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    margin-right: 5px;
    @each $c, $i in $bgc {
      &.color-#{$i} {
        background: $c;
      }
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
</style>
